import { createDayHours } from './utils.js'


let timeline;
const scrollMap = [];
export const $pointer = $('<div class="time-pointer"><div class="time-arrow"></div></div>');
export const $desc = $('<div class="datetime-description">00:00:00</div>');
const timeAxisTemplate = (width) => $(`
      <div class="time-axis">
        <div class="time-scroller" style="width: ${width}px;"></div>
        <div class="time-timeline" style="width: ${width}px;"></div>
      </div>
    `)

export default class Timeline {
    #width;
    $container;
    $timeAxis;

    static getInstance () {
        return timeline || (timeline =  new Timeline());
    }

    /**
     * 初始化时间轴
     *
     * @param width
     * @return {*}
     */
    init (width) {
        const $timeAxis = timeAxisTemplate(width);
        const $scroller = $timeAxis.find('.time-scroller');

        this.#width = width;
        this.$timeAxis = $timeAxis;
        this.renderTimeline();

        if (!$scroller.children().has($pointer).length) {
            $scroller.append($pointer);
            $scroller.append($desc);
        }


        return this.$timeAxis
    }

    /**
     * 根据不同的宽度，渲染不同的时间轴演示
     */
    renderTimeline = () => {
        const $timeline = $(this.$timeAxis).find('.time-timeline')
        if (!$timeline.length) return

        // console.log(this.#width)
        if (this.#width >= 7200) {
            const hours = createDayHours(24, (item, index) => {
                const children = new Array(50).fill({ type: 'minute-longer' }).map((item, index) => ({
                    ...item,
                    type: index % 10 ? `minute` : `minute-longer`,
                    text: index % 10 ? `` : `0${index}`
                }));
                const text = (index < 10) ? `0${index}` : `${index}`
                const half = { type: 'hour-half-longer', text: '' }
                if (this.#width >= 1600) half.text += `${text}:30`
                children.splice(children.length / 2, children.length % 2, half)
                return ({ ...item, children, text })
            });
            const timeline = hours.map(this.createTimeline)
            $timeline.html(timeline);
        } else if (this.#width >= 3600) {
            const hours = createDayHours(24, (item, index) => {
                const defaultArray = []
                if (this.#width > 4800) defaultArray.push({ type: 'minute' })
                if (this.#width > 6000) defaultArray.push({ type: 'minute' })
                let children = new Array(11).fill({ type: 'minute' }).reduce((prev, next, index) => {
                    prev.push({
                        ...next,
                        text: index % 2 ? `${ (index + 1) / 2 }0` : ''
                    })
                    if (this.#width > 4800) prev.push(next)
                    if (this.#width > 6000) prev.push(next)
                    return prev;
                }, defaultArray);
                const text = (index < 10) ? `0${index}` : `${index}`
                const half = { type: 'hour-half', text: `${text}:30` }
                children.splice(children.length / 2, children.length % 2, half)
                return ({ ...item, children, text })
            });
            const timeline = hours.map(this.createTimeline)
            $timeline.html(timeline);
        } else if (this.#width >= 800) {
            const hours = createDayHours(24, (item, index) => {
                const children = new Array(5).fill({ type: 'minute' });
                const text = (index < 10) ? `0${index}` : `${index}`
                const half = { type: 'hour-half', text: '' }
                if (this.#width >= 1600) half.text += `${text}:30`
                children.splice(children.length / 2, children.length % 2, half)
                return ({ ...item, children, text })
            });
            const timeline = hours.map(this.createTimeline)
            $timeline.html(timeline);
        } else  if (this.#width >= 400) {
            const children = new Array(~~(((this.#width) || 400) / 100)).fill({ type: 'minute' });
            children.splice(children.length / 2, children.length % 2, { type: 'hour-half' })
            const hours = createDayHours(12, (item, index) => ({
                ...item,
                children,
                text: (index * 2 < 10) ? `0${index * 2}` : `${index * 2}`
            }));
            const timeline = hours.map(this.createTimeline)

            $timeline.html(timeline);
        } else {
            const children = new Array(~~((this.#width || 100) / 100)).fill({ type: 'minute' })
            const hours = createDayHours(6, (item, index) => ({
                ...item,
                children,
                text: (index * 4 < 10) ? `0${index * 4}` : `${index * 4}`
            }));
            const timeline = hours.map(this.createTimeline)

            $timeline.html(timeline);
            console.log(hours, timeline)
        }
    }

    /**
     * 创建时间轴节点
     *
     * @param type
     * @param text
     * @param children
     * @return {string}
     */
    createTimeline = ({ type, text = '', children } = {}) => {
        let innerHtml = ''

        switch (type) {
            case 'hour': {
                if (Array.isArray(children)) innerHtml = children.map(this.createTimeline)?.join('')
                return `<div class="timeline-hour"><span class="timeline-hour-text">${text}</span>${ innerHtml }</div>`
            }
            case 'hour-half': {
                innerHtml = `<span class="timeline-hour-half-text">${text}</span>`
                return `<div class="timeline-minute timeline-hour-half">${ innerHtml }</div>`
            }
            case 'hour-half-longer': {
                innerHtml = `<span class="timeline-hour-half-text">${text}</span>`
                return `<div class="timeline-minute time-longer timeline-hour-half">${ innerHtml }</div>`
            }
            case 'minute': {
                innerHtml = `<span class="timeline-minute-text">${text}</span>`
                return `<div class="timeline-minute">${innerHtml}</div>`
            }
            case 'minute-longer': {
                innerHtml = `<span class="timeline-minute-text">${text}</span>`
                return `<div class="timeline-minute time-longer">${innerHtml}</div>`
            }
            default: return ''
        }
    }

    movePointer = (left) => {
        const __left = pointerPositionLeft || `${left}%`;
        const $description = $(this.container).find('.datetime-description');
        const startTime = this.getStartTime(startLeft);

        console.log('startTime: => ', __left, startTime)
        $scroller.find('.time-pointer').css('left', __left);
        $description.css('left', __left);

        if (startTime !== 'Invalid Date') $description.text(startTime);
    }

    renderScroller = (timelines = [], cb) => {
        const max = 235959
        const $scroller = $(this.container).find('.time-scroller');
        let ScrollerWidth = $scroller.width();

        scrollMap.length = 0;
        $scroller.find('.time-axis-scroll').remove();
        if (!ScrollerWidth) ScrollerWidth = $(this.container).width();

        const item = {
            left: '50%',
            width: '235px',
        }
        timelines.map((item, index) => {
            const [start, end] = WidgetSimple.getIntervalTime(item);
            const width = end - start;
            const __width = ~~((width / max) * 10000) / 100
            const left = ~~(start / max * 10000) / 100
            const startLeft = left / 100 * ScrollerWidth

            scrollMap.push([startLeft, (left + __width) / 100 * ScrollerWidth])
            console.log(start, end, width) // ~~(0.3333333 * 10000) / 100
            $scroller.append(
                $('<div class="time-axis-scroll"/>')
                    .css('width', `${__width}%`)
                    .css('left', `${left}%`)
            );

            cb && cb($scroller)
        });
    }
}